package com.zanbo.hot100.add_two_numbers;

import com.zanbo.structure.data.ListNode;
import com.zanbo.structure.utils.ListNodeUtil;

/**
 * @author zanbo
 * @program Solution
 * @since 2021-12-22 下午 7:16
 */
public class Add_two_numbers {
    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode listNode = solution.addTwoNumbers(ListNodeUtil.getListNode(), ListNodeUtil.getListNode());
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

}

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode x = head;
        int big = 0;
        while (l1 != null || l2 != null) {
            int a = l1 != null ? l1.val : 0;
            int b = l2 != null ? l2.val : 0;
            int sum = a + b + big;
            big = sum / 10;
            ListNode listNode = new ListNode(sum % 10);
            x.next = listNode;
            x = x.next;
            if (l1!=null) {
                l1 = l1.next;
            }
            if (l2!=null) {
                l2 = l2.next;
            }
        }
        if (big > 0) {
            x.next = new ListNode(big);
        }
        return head.next;
    }
}